package com.huishu.commons.utlis;

import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamUtils {

    /**
     * Description: Java8 Stream分割list集合
     *
     * @param list      集合数据
     * @param splitSize 几个分割一组
     * @return 集合分割后的集合
     */
    public static <T> List<List<T>> splitList(List<T> list, int splitSize) {
        //判断集合是否为空
        if (CollectionUtils.isEmpty(list))
            return Collections.emptyList();
        //计算分割后的大小
        int maxSize = (list.size() + splitSize - 1) / splitSize;
        //开始分割
        return Stream.iterate(0, n -> n + 1)
                .limit(maxSize)
                .parallel()
                .map(a -> list.parallelStream().skip(a * splitSize).limit(splitSize).collect(Collectors.toList()))
                .filter(b -> !b.isEmpty())
                .collect(Collectors.toList());
    }

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>(1001);
        for (int i = 0; i < 43; i++) {
            list.add(i);
        }
        int splitSize = 100;

        List<List<Integer>> splitList = StreamUtils.splitList(list, splitSize);
        for (List<Integer> integers : splitList) {
            System.out.println(integers.size());
        }

    }
}
